package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Course;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.exceptions.StudentNoException;
import cn.kgc.vue.mapper.CourseMapper;
import cn.kgc.vue.mapper.StudentMapper;
import cn.kgc.vue.service.StudentService;
import cn.kgc.vue.vo.StudentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_student】的数据库操作Service实现
* @createDate 2024-04-17 10:31:01
*/
@Service
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>implements StudentService{


    @Resource
    private CourseMapper courseMapper;

    @Override
    public ResponseResult studentPage(QueryCondition<Student> queryCondition) {

        Page<Student> studentPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        String studentNo = queryCondition.getSearchParams().getStudentNo();
        String clazz = queryCondition.getSearchParams().getClazz();

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotBlank(studentNo),Student::getStudentNo,studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz,clazz)
                .orderByDesc(Student::getId);

        baseMapper.selectPage(studentPage,lambda);

        List<StudentVO> collect = studentPage.getRecords().stream()
                .map(student -> {
                    StudentVO studentVO = new StudentVO();
                    BeanUtils.copyProperties(student, studentVO);
                    // 根据学生课程id 查询课程名称
                    Integer courseId = student.getCourseId();
                    // String courseName = courseMapper.selectById(courseId).getCourseName();
                    Course course = courseMapper.findById(courseId);
                    studentVO.setCourseName(course.getCourseName());
                    return studentVO;
                }).collect(Collectors.toList());


        return ResponseResult.success()
                .data("total",studentPage.getTotal())
                .data("tableData",collect);
    }

    @Override
    public ResponseResult importStudent(MultipartFile file) throws Exception {

        // 判定文件是否为空文件
        if (file.isEmpty()){
            return ResponseResult.fail().message("请选择文件");
        }

        InputStream inputStream = file.getInputStream();
        // 设置导入参数
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);  //  设置标题行的行数
        importParams.setHeadRows(1);// 设置表头行的行数

        List<Student> students = ExcelImportUtil.importExcel(inputStream, Student.class, importParams);

        students.forEach(student -> {
            // 判定学号是否已经存在
            String studentNo = student.getStudentNo();
            LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
            lambda.eq(Student::getStudentNo,studentNo);
            Student stu = baseMapper.selectOne(lambda);
            if (ObjectUtils.isNotNull(stu)){
                throw  new StudentNoException(studentNo+"学号已存在");
            }

            baseMapper.insert(student);
        });

        return ResponseResult.success().message("批量导入成功");
    }

    @Override
    public void exportStudent(HttpServletResponse response, Map<String,Object> exportParam) throws IOException {

        Object studentNo = exportParam.get("studentNo");
        Object clazz = exportParam.get("clazz");

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(ObjectUtils.isNotNull(studentNo),Student::getStudentNo,studentNo)
                .eq(ObjectUtils.isNotNull(clazz),Student::getClazz,clazz);

        List<Student> students = baseMapper.selectList(lambda);

        //创建导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("学生信息表");
        exportParams.setSheetName("学生信息");

        // 工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, students);
        ServletOutputStream outputStream = response.getOutputStream();
        // 写出工作簿
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }


}




